import { createLoading } from '/@/components/Loading/src/createLoading';
import type { LoadingProps } from '/@/components/Loading/src/typing';
import { messageFn } from '/@/store/utils';

interface Params<T> {
  api: Fn;
  params?: T;
  message?: string;
  loadingPorps?: {
    props?: Partial<LoadingProps>;
    target?: HTMLElement;
  }
}

export const useRequestApi = async <T = any>({
  api,
  params,
  message,
  loadingPorps,
}: Params<T>) => {
  const { props = { tip: '加载中' }, target = document.body } = loadingPorps || {}
  
  const instance = createLoading(props, target);
  instance.open()
  try {
    let { code, msg, data } = await api(params)
    if (code === undefined) {
      code = data.code
      msg = data.msg
      data = data.data
    }
    console.log(code, msg, data);
    
    if (code === 0) {
      return data
    } else {
      messageFn('error', message || msg)
      return Promise.reject(msg) 
    }
  } catch(err) {
    console.log('err-', err);
    return Promise.reject(err)
  } finally {
    instance.close()
  }
}